package middleware

import (
	"fmt"
	"net/http"
	"reflect"
	"regexp"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/locales/en"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	enTranslations "github.com/go-playground/validator/v10/translations/en"
	chTranslations "github.com/go-playground/validator/v10/translations/zh"
)

var Trans ut.Translator

// loca 通常取决于 http 请求头的 'Accept-Language'
func transInit(local string) (err error) {
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		zhT := zh.New() //chinese
		enT := en.New() //english
		uni := ut.New(enT, zhT, enT)

		var o bool
		Trans, o = uni.GetTranslator(local)
		if !o {
			return fmt.Errorf("uni.GetTranslator(%s) failed", local)
		}
		//register translate
		// 注册翻译器
		switch local {
		case "en":
			err = enTranslations.RegisterDefaultTranslations(v, Trans)
		case "zh":
			//注册一个函数，获取struct tag里自定义的label作为字段名
			v.RegisterTagNameFunc(func(fld reflect.StructField) string {
				name := fld.Tag.Get("label")
				return name
			})
			err = chTranslations.RegisterDefaultTranslations(v, Trans)
		default:
			err = enTranslations.RegisterDefaultTranslations(v, Trans)
		}

		return
	}
	return
}

// 设置翻译器
func SetTranslator(c *gin.Context) {
	local := c.GetHeader("Accept-Language")
	// 使用正则表达式匹配 "zh-CN" 或 "zh"，不区分大小写
	re := regexp.MustCompile(`(?i)\bzh(-CN)?\b`)
	if local == "" || local == "zh-CN" || re.MatchString(local) {
		local = "zh" // 默认语言
	}

	if err := transInit(local); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"msg": "Translation init failed"})
		c.Abort()
		return
	}

	c.Next()
}

func GetFirstErrorMessage(errs validator.ValidationErrors) string {
	for _, err := range errs {
		// 只返回第一个翻译后的错误消息
		return err.Translate(Trans)
	}
	return "未知错误" // 如果没有错误，返回默认错误消息
}
